<template>
  <tbc-dialog ref="dialog" title="订单支付" @confirm="formSubmit" :loading="loading">
    <tbc-dynamic-form :form="dynamicForm" class="compact"/>
  </tbc-dialog>
</template>
<script lang="ts">
import {defineComponent, reactive, ref, Ref, toRefs} from 'vue'
import http from '@/plugin/http'
import {ElMessage} from 'element-plus'

export default defineComponent({

  name: 'order-payment',

  emits: ['success'],

  setup(props, {emit}) {
    const dialog: Ref = ref(null)
    const state = reactive({
      loading: false,
      form: {order_sn: '', reason: ''},
      dynamicForm: [
        {label: '订单', type: 'input', field: 'order_sn', value: '', disabled: true},
        // {
        //   label: '支付方式', type: 'radio', field: 'pay_type', value: 1, options: [
        //     {label: '线下支付', value: 1}
        //   ]
        // },

        {label: '支付流水', type: 'input', field: 'pay_type', value: '', readonly: true, default: '线下支付'},
        {label: '支付流水', type: 'input', field: 'out_trade_no', value: ''},
        {label: '备注', type: 'textarea', field: 'reason', value: ''},
      ]
    })

    // 显示窗口
    const show = (data: { [k: string]: string }) => {
      state.dynamicForm.forEach((item: Record<string, any>) => {
        item.value = item.default !== undefined ? item.default : ''
        if (data[item.field] !== undefined) item.value = data[item.field]
      })
      dialog.value.show()
    }

    // 提交
    const formSubmit = async () => {
      let form: Record<string, any> = {};
      state.dynamicForm.forEach(item => form[item.field] = item.value)
      state.loading = true
      const res = await http.post('/order/payment', form)
      state.loading = false
      if (res.data.code !== 0) return ElMessage.error(res.data.message);
      ElMessage.success(res.data.message as string)
      emit('success', form)
      dialog.value.close()
    }

    return {
      ...toRefs(state),
      dialog,
      show,
      formSubmit
    }
  }
})
</script>